<?php

namespace app\admin\controller;

use think\Db;
use think\Request;

/**
 * 症状管理控制器
 */
class Symptom extends Base
{
    /**
     * 获取症状列表
     */
    public function index()
    {
        $page = input('page', 1);
        $limit = input('limit', 20);
        $keyword = input('keyword', '');
        $categoryId = input('category_id', '');

        $where = [];
        if (!empty($keyword)) {
            $where[] = [
                's.name_zh_cn|s.name_en_us|s.name_ja_jp|s.name_be_by',
                'like',
                '%' . $keyword . '%'
            ];
        }

        if (!empty($categoryId)) {
            $where['s.category_id'] = $categoryId;
        }

        // 关联查询分类信息
        $list = Db::name('symptoms')
            ->alias('s')
            ->join('symptom_categories sc', 's.category_id = sc.id')
            ->where($where)
            ->field('s.*,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
            ->order('s.category_id asc, s.sort_order asc, s.id asc')
            ->paginate($limit, false, ['page' => $page]);

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => [
                'list' => $list->items(),
                'total' => $list->total(),
                'page' => $page,
                'limit' => $limit
            ]
        ]);
    }

    /**
     * 获取单个症状
     */
    public function read()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        $symptom = Db::name('symptoms')
            ->alias('s')
            ->join('symptom_categories sc', 's.category_id = sc.id')
            ->where('s.id', $id)
            ->field('s.*,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
            ->find();

        if (!$symptom) {
            return json(['code' => 1, 'msg' => '数据不存在']);
        }

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $symptom
        ]);
    }

    /**
     * 创建症状
     */
    public function save()
    {
        $data = input('post.');

        // 定义允许插入的字段（只包含症状表的字段）
        $allowedFields = [
            'category_id',
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by',
            'description_zh_cn', 'description_en_us', 'description_ja_jp', 'description_be_by',
            'keywords_zh_cn', 'keywords_en_us', 'keywords_ja_jp', 'keywords_be_by',
            'sort_order',
            'is_active'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }

        // 验证必填字段
        $required = [
            'category_id',
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($filteredData[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }

        // 检查分类是否存在
        $category = Db::name('symptom_categories')->find($filteredData['category_id']);
        if (!$category) {
            return json(['code' => 1, 'msg' => '症状分类不存在']);
        }

        // 检查中文名称是否重复
        $existingSymptom = Db::name('symptoms')
            ->where('name_zh_cn', $filteredData['name_zh_cn'])
            ->find();
        if ($existingSymptom) {
            return json(['code' => 1, 'msg' => '症状名称"' . $filteredData['name_zh_cn'] . '"已存在']);
        }

        // 设置默认值
        if (!isset($filteredData['sort_order'])) {
            $filteredData['sort_order'] = 0;
        }
        if (!isset($filteredData['is_active'])) {
            $filteredData['is_active'] = 1;
        }

        $filteredData['created_at'] = date('Y-m-d H:i:s');
        $filteredData['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('symptoms')->insert($filteredData);

        if ($result) {
            return json(['code' => 0, 'msg' => '创建成功']);
        } else {
            return json(['code' => 1, 'msg' => '创建失败']);
        }
    }

    /**
     * 更新症状
     */
    public function update()
    {
        $id = input('id');
        $data = input('post.');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 定义允许更新的字段（只包含症状表的字段）
        $allowedFields = [
            'category_id',
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by',
            'description_zh_cn', 'description_en_us', 'description_ja_jp', 'description_be_by',
            'keywords_zh_cn', 'keywords_en_us', 'keywords_ja_jp', 'keywords_be_by',
            'sort_order',
            'is_active'
        ];

        // 过滤数据，只保留允许的字段
        $filteredData = [];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $filteredData[$field] = $data[$field];
            }
        }

        // 验证必填字段
        $required = [
            'category_id',
            'name_zh_cn', 'name_en_us', 'name_ja_jp', 'name_be_by'
        ];

        foreach ($required as $field) {
            if (empty($filteredData[$field])) {
                return json(['code' => 1, 'msg' => "字段 {$field} 不能为空"]);
            }
        }

        // 检查分类是否存在
        $category = Db::name('symptom_categories')->find($filteredData['category_id']);
        if (!$category) {
            return json(['code' => 1, 'msg' => '症状分类不存在']);
        }

        // 检查中文名称是否重复（排除当前记录）
        $existingSymptom = Db::name('symptoms')
            ->where('name_zh_cn', $filteredData['name_zh_cn'])
            ->where('id', '<>', $id)
            ->find();
        if ($existingSymptom) {
            return json(['code' => 1, 'msg' => '症状名称"' . $filteredData['name_zh_cn'] . '"已存在']);
        }

        $filteredData['updated_at'] = date('Y-m-d H:i:s');

        $result = Db::name('symptoms')->where('id', $id)->update($filteredData);

        if ($result !== false) {
            return json(['code' => 0, 'msg' => '更新成功']);
        } else {
            return json(['code' => 1, 'msg' => '更新失败']);
        }
    }

    /**
     * 删除症状
     */
    public function delete()
    {
        $id = input('id');

        if (empty($id)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 检查是否被汤药引用
        $formulaCount = Db::name('formulas')
            ->where('main_symptom_ids', 'like', '%,' . $id . ',%')
            ->whereOr('main_symptom_ids', 'like', $id . ',%')
            ->whereOr('main_symptom_ids', 'like', '%,' . $id)
            ->whereOr('main_symptom_ids', $id)
            ->whereOr('side_symptom_ids', 'like', '%,' . $id . ',%')
            ->whereOr('side_symptom_ids', 'like', $id . ',%')
            ->whereOr('side_symptom_ids', 'like', '%,' . $id)
            ->whereOr('side_symptom_ids', $id)
            ->count();

        if ($formulaCount > 0) {
            return json(['code' => 1, 'msg' => '该症状被汤药引用，无法删除']);
        }

        $result = Db::name('symptoms')->delete($id);

        if ($result) {
            return json(['code' => 0, 'msg' => '删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '删除失败']);
        }
    }

    /**
     * 批量删除
     */
    public function deleteMultiple()
    {
        $ids = input('ids');

        if (empty($ids) || !is_array($ids)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }

        // 检查是否被汤药引用
        foreach ($ids as $id) {
            $formulaCount = Db::name('formulas')
                ->where('main_symptom_ids', 'like', '%,' . $id . ',%')
                ->whereOr('main_symptom_ids', 'like', $id . ',%')
                ->whereOr('main_symptom_ids', 'like', '%,' . $id)
                ->whereOr('main_symptom_ids', $id)
                ->whereOr('side_symptom_ids', 'like', '%,' . $id . ',%')
                ->whereOr('side_symptom_ids', 'like', $id . ',%')
                ->whereOr('side_symptom_ids', 'like', '%,' . $id)
                ->whereOr('side_symptom_ids', $id)
                ->count();

            if ($formulaCount > 0) {
                return json(['code' => 1, 'msg' => '选中的症状中有被汤药引用的，无法删除']);
            }
        }

        $result = Db::name('symptoms')->whereIn('id', $ids)->delete();

        if ($result) {
            return json(['code' => 0, 'msg' => '批量删除成功']);
        } else {
            return json(['code' => 1, 'msg' => '批量删除失败']);
        }
    }

    /**
     * 根据分类获取症状列表（用于下拉选择）
     */
    public function getByCategoryId()
    {
        $categoryId = input('category_id');

        $where = ['is_active' => 1];
        if (!empty($categoryId)) {
            $where['category_id'] = $categoryId;
        }

        $list = Db::name('symptoms')
            ->where($where)
            ->field('id,name_zh_cn,name_en_us,name_ja_jp,name_be_by,category_id')
            ->order('sort_order asc, id asc')
            ->select();

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => $list
        ]);
    }

    /**
     * 获取所有启用的症状（用于汤药配置）
     */
    public function getActiveList()
    {
        $list = Db::name('symptoms')
            ->alias('s')
            ->join('symptom_categories sc', 's.category_id = sc.id')
            ->where('s.is_active', 1)
            ->field('s.id,s.name_zh_cn,s.name_en_us,s.name_ja_jp,s.name_be_by,s.category_id,sc.name_zh_cn as category_name_zh_cn,sc.name_en_us as category_name_en_us,sc.name_ja_jp as category_name_ja_jp,sc.name_be_by as category_name_be_by')
            ->order('s.category_id asc, s.sort_order asc, s.id asc')
            ->select();

        // 按分类分组
        $grouped = [];
        foreach ($list as $item) {
            $categoryId = $item['category_id'];
            if (!isset($grouped[$categoryId])) {
                $grouped[$categoryId] = [
                    'category_id' => $categoryId,
                    'category_name_zh_cn' => $item['category_name_zh_cn'],
                    'category_name_en_us' => $item['category_name_en_us'],
                    'category_name_ja_jp' => $item['category_name_ja_jp'],
                    'category_name_be_by' => $item['category_name_be_by'],
                    'symptoms' => []
                ];
            }
            $grouped[$categoryId]['symptoms'][] = [
                'id' => $item['id'],
                'name_zh_cn' => $item['name_zh_cn'],
                'name_en_us' => $item['name_en_us'],
                'name_ja_jp' => $item['name_ja_jp'],
                'name_be_by' => $item['name_be_by']
            ];
        }

        return json([
            'code' => 0,
            'msg' => 'success',
            'data' => array_values($grouped)
        ]);
    }
}
